package com.lw.leetcode.dp.c;

/**
 * Created with IntelliJ IDEA.
 * 123. 买卖股票的最佳时机 III
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/17 11:37
 */
public class MaxProfit123 {

    public static void main(String[] args) {
        MaxProfit123 test = new MaxProfit123();
        int[] arr = {1, 2, 3, 4, 5};
//        int[] arr = {2,1,4,5,2,9,7};
        int i = test.maxProfit(arr);

        System.out.println(i);
    }

    public int maxProfit(int[] prices) {
        int length = prices.length;
        if (length == 1) {
            return 0;
        }
        if (length == 2) {
            return Math.max(0, prices[1] - prices[0]);
        }

        int max = Math.max(Math.max(0, prices[2] - prices[1]), Math.max(prices[2] - prices[0], prices[1] - prices[0]));
        if (length == 3) {
            return max;
        }
        int a2 = -(Math.min(prices[0], Math.min(prices[1], prices[2])));
        int b2 = max;
        int c2 = -prices[0] + prices[1] - prices[2];
        int d2 = Integer.MIN_VALUE;
        int a1 = 0;
        int b1 = 0;
        int c1 = 0;
        int d1 = 0;
        for (int i = 3; i < length; i++) {
            int p = prices[i];
            a1 = Math.max(-p, a2);
            b1 = Math.max(b2, a2 + p);
            c1 = Math.max(c2, b2 - p);
            d1 = Math.max(d2, c2 + p);
            a2 = a1;
            b2 = b1;
            c2 = c1;
            d2 = d1;
        }
        return Math.max(Math.max(0, b1), d1);
    }
}
